package j.util.jdbc;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * jdbc跨平台工具类
 * User: jason
 * Date: 13-9-24 上午9:37
 */
public class JdbcPlatform {
    private JdbcPlatform(){}
    private static final JdbcPlatform instance = new JdbcPlatform();
    private DatabaseType databaseType = null;

    public static DatabaseType getDatabaseType(DataSource dataSource){
        if(instance.databaseType == null){
            synchronized (JdbcPlatform.class){
                if(instance.databaseType == null){
                    Connection conn = null;
                    try{
                        conn = dataSource.getConnection();
                        /*DatabaseMetaData metaData = conn.getMetaData();
                        String s = metaData.getDatabaseProductName();
                        s = s.toLowerCase();
                        if(s.contains("mysql")){
                            instance.databaseType = DatabaseType.MYSQL;
                        }else if(s.contains("microsoft")){
                            instance.databaseType = DatabaseType.MSSQL;
                        }else if(s.contains("oracle")){
                            instance.databaseType = DatabaseType.ORACLE;
                        }*/
                        instance.databaseType = DatabaseType.parseDatabaseType(conn.getMetaData().getDatabaseProductName());
                    }catch (SQLException e){
                        throw new RabbitJdbcException(String.format("从数据源中获取数据连接时出现异常,异常:%s.",e.getMessage()));
                    }
                    finally {
                        if(conn!=null){
                            JdbcUtils.free(conn, null);
                        }
                    }
                }
            }
        }
        return instance.databaseType;
    }
}
